import {Component} from 'react';
import {connect} from 'react-redux';
import axios from 'axios';
import * as Notification from 'modules/notification/actions';
import Session from 'modules/auth/session';
import styled from "styled-components";
import {Button, Empty, Input, Modal, PageHeader, Select, Table} from 'antd';

const {Option} = Select;

const ButtonGroup = Button.Group;
const Outer = styled.div`
  border:1px solid #ececec;
  margin:20px;
   box-shadow: 3px 3px 6px rgba(0,0,0,0.1), 3px 3px 6px rgba(0,0,0,0.2);
`;


const Conten = styled.div`
  margin: 20px;
  box-sizing:border-box;
`;
const ContenTiTle = styled.div`
padding:1px;
 background:#f1f1f1;
`;
const ContenList = styled.div`
  display:flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
`;
const CenterName = styled.div`
  width:180px;
  font-size:14px;
  color:#000;
  text-align:right;
  padding-right:15px;
`;
const CenterInputOuter = styled.div`
  width:400px;
  font-size:14px;
  color:#000;
`;

let tipsObj = {
    netPortSymbol: "网口标志不能为空，且不可重复",
    ipAddressSymbol: "IP链路名称不能为空",
    VlanId: "VlanId不能为空",
    ipAddress: "请输入正确的IP地址，例：127.0.0.1",
    netmask: "请输入正确的子网掩码，例：255.255.255.0",
    virtualIpBoolean: "是否虚拟IP",
    mtu: "MTU不能为空",
    OpenNetPortBoolean: "网口是否启用，默认启用",
};

class Collection extends Component {
    state = {
        search: '',
        document: {
            action: '',
            visible: false,
            dimmed: false
        },
        confirm: {
            visible: false,
            imsi: ''
        },
        view: {
            visible: false,
            disableOnClickOutside: false,
            imsi: ''
        },
        visible: false,
        modelTitle: '新增DP参数',
        configData: {},
        selectedRowKeys: [], // Check here to configure the default column
        loading: false,
        ID: '',
        dpData: [],
        netPortSymbol: '',
        ipAddressSymbol: '',
        VlanId: '',
        ipAddress: '',
        netmask: '',
        virtualIpBoolean: 'False',
        mtu: '',
        OpenNetPortBoolean: 'Enable',

    };


    onSelectChange = selectedRowKeys => {
        this.setState({selectedRowKeys});
    };


    componentWillMount() {

        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/dp',
            params: {},
            // data
        }).then(res => {
            var configData = res.data[0].config
            $this.setState({
                    configData: res.data[0],
                    dpData: configData.dpData || []
                }
            )

        })
    }

    getSData = () => {
        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/dp',
            params: {},
            // data
        }).then(res => {
            var configData = res.data[0].config
            $this.setState({
                    configData: res.data[0],
                    dpData: configData.dpData || []

                }
            )

            dispatch(Notification.success({
                title: '提示',
                message: `DP参数列表刷新成功！`
            }));
        })
    }

    handleOk = e => {
        let $this = this

        let editorBol = false
        if (this.state.modelTitle == '修改DP参数') {
            editorBol = true
        }
        const {dispatch} = this.props
        let sendData = JSON.parse(JSON.stringify(this.state.configData))
        sendData.config.dpData = sendData.config.dpData || []
        let sendLine = {}
        sendLine.netPortSymbol = this.state.netPortSymbol
        sendLine.ipAddressSymbol = this.state.ipAddressSymbol
        sendLine.VlanId = this.state.VlanId
        sendLine.ipAddress = this.state.ipAddress
        sendLine.netmask = this.state.netmask
        sendLine.virtualIpBoolean = this.state.virtualIpBoolean
        sendLine.mtu = this.state.mtu
        sendLine.OpenNetPortBoolean = this.state.OpenNetPortBoolean

        if (sendLine.netPortSymbol == '' ||
            sendLine.ipAddressSymbol == '' ||
            sendLine.VlanId == '' ||
            sendLine.ipAddress == '' ||
            sendLine.netmask == '' ||
            sendLine.virtualIpBoolean == '' ||
            sendLine.mtu == '' ||
            sendLine.OpenNetPortBoolean == ''
        ) {
            dispatch(Notification.error({
                title: '提示', autoDismiss: 4,
                message: `DP参数的值不能为空！`
            }));
            return false
        }

        function isValidIP(ip) {
            var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
            return reg.test(ip);
        }

        if (isValidIP(sendLine.ipAddress) == false) {
            dispatch(Notification.error({
                title: '提示', autoDismiss: 4,
                message: tipsObj.ipAddress
            }));
            return false
        }

        if (isValidIP(sendLine.netmask) == false) {
            dispatch(Notification.error({
                title: '提示', autoDismiss: 4,
                message: tipsObj.netmask
            }));
            return false
        }

        let hasId = false
        sendData.config.dpData.forEach(a => {
            if (sendLine.netPortSymbol == a.netPortSymbol) {
                if (editorBol) {
                    if ($this.state.ID != a.ID) {
                        hasId = true
                    }
                } else {
                    hasId = true
                }
            }
        })
        if (hasId) {
            dispatch(Notification.error({
                title: '提示',
                autoDismiss: 4,
                message: '网口标志重复，系统中已有网口标志为' + sendLine.netPortSymbol + '的数据，请修正！',
            }));
            return false
        }


        if (editorBol) {

            sendData.config.dpData.forEach(a => {
                if (a.ID == $this.state.ID) {
                    a.netPortSymbol = sendLine.netPortSymbol
                    a.ipAddressSymbol = sendLine.ipAddressSymbol
                    a.VlanId = sendLine.VlanId
                    a.ipAddress = sendLine.ipAddress
                    a.netmask = sendLine.netmask
                    a.virtualIpBoolean = sendLine.virtualIpBoolean
                    a.OpenNetPortBoolean = sendLine.OpenNetPortBoolean
                    a.mtu = sendLine.mtu
                }
            })
        } else {
            sendLine.key = parseInt(Math.random() * 10000000000)
            sendLine.ID = sendData.config.dpData.length == 0 ? 1 : (sendData.config.dpData[sendData.config.dpData.length - 1].ID + 1)
            sendData.config.dpData.push(sendLine)
        }

        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "PATCH",
            url: '/dp/' + sendData._id,
            data: sendData,
            //
        }).then(res => {
            this.handleCancel()
            var configData = res.data.config
            $this.setState({
                    configData: res.data,
                    dpData: configData.dpData || []
                }
            )
            dispatch(Notification.success({
                title: '提示',
                message: `DP参数配置成功！`
            }));
        })
    }

    showModal = () => {
        this.setState({
            visible: true,
        });
    };


    handleCancel = e => {
        this.setState({
            visible: false,
        });
    };


    _handleChange(e) {
        // 获取 input 元素上的value
        let name = e.target.name;
        let value = e.target.value;
        this.setState({
            [name]: value
        })
    };

    _handleOpenNetPortBooleanChange(value) {
        this.setState({
            OpenNetPortBoolean: value
        })
    };

    _handleVirtualIpBooleanChange(value) {
        this.setState({
            virtualIpBoolean: value
        })
    };

    addRow = () => {
        this.setState({
            modelTitle: '新增DP参数',
            netPortSymbol: '',
            ipAddressSymbol: '',
            VlanId: '',
            ipAddress: '',
            netmask: '',
            virtualIpBoolean: 'False',
            mtu: '',
            OpenNetPortBoolean: 'Enable',
        })
        this.showModal()
    }

    editRow = (row, e) => {

        this.setState({
            modelTitle: '修改DP参数',
            ID: row.ID,
            netPortSymbol: row.netPortSymbol,
            ipAddressSymbol: row.ipAddressSymbol,
            VlanId: row.VlanId,
            ipAddress: row.ipAddress,
            netmask: row.netmask,
            virtualIpBoolean: row.virtualIpBoolean,
            mtu: row.mtu,
            OpenNetPortBoolean: row.OpenNetPortBoolean,
        })
        this.showModal()
    }

    render() {
        let $this = this
        const {loading, selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;


        const columns = [
            {
                title: '操作',
                dataIndex: '',
                key: 'y',
                width: 240,
                render: (text, record) => {
                    return (
                        <div>

                            <ButtonGroup>

                                <Button type="primary" onClick={(e) => this.editRow(record, e)}>修改</Button>
                                <Button type="danger" onClick={(e) => this.delRow(record, e)}>删除</Button>
                            </ButtonGroup>
                        </div>
                    )
                },
            },
            {
                title: 'IP链路ID',
                dataIndex: 'ID'
            },
            {
                title: '网口标志',
                dataIndex: 'netPortSymbol'
            },
            {
                title: 'IP链路名称',
                dataIndex: 'ipAddressSymbol'
            },
            {
                title: 'VlanId',
                dataIndex: 'VlanId'
            },
            {
                title: 'IP地址',
                dataIndex: 'ipAddress'
            },
            {
                title: '子网掩码',
                dataIndex: 'netmask'
            },
            {
                title: '是否虚拟IP',
                dataIndex: 'virtualIpBoolean'
            },
            {
                title: 'MTU',
                dataIndex: 'mtu'
            },
            {
                title: '网口是否启用',
                dataIndex: 'OpenNetPortBoolean'
            },

        ];


        return (
            <div>
                <PageHeader
                    style={{
                        border: '1px solid rgb(235, 237, 240)',
                    }}
                    title="DP参数列表"
                />
                <Outer>
                    <Conten>
                        <div>
                            <div style={{marginBottom: 16}}>
                                <Button type="success" onClick={this.addRow}>
                                    新增
                                </Button>
                                <span>&nbsp;&nbsp;</span>
                                <Button type="primary" onClick={this.getSData}>
                                    刷新
                                </Button>
                                <span>
                                    &nbsp;&nbsp;共{this.state.dpData.length}条数据&nbsp;&nbsp;&nbsp;&nbsp;
                                </span>
                                <span
                                    style={{marginLeft: 8}}>{hasSelected ? `Selected ${selectedRowKeys.length} items` : ''} </span>
                            </div>
                            <Table
                                locale={
                                    {
                                        emptyText: () => {
                                            return (
                                                <Empty
                                                    description={
                                                        <span>暂无数据</span>
                                                    }
                                                />
                                            )
                                        }
                                    }
                                }
                                columns={columns} dataSource={this.state.dpData}/>
                        </div>
                    </Conten>
                </Outer>


                <Modal
                    title={this.state.modelTitle}
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText="确认"
                    width={800}
                    cancelText="取消"
                >
                    <ContenTiTle>
                        <ContenList>
                            <CenterName><strong>参数名</strong></CenterName>
                            <CenterInputOuter>
                                <strong>值</strong>
                            </CenterInputOuter>
                        </ContenList>
                    </ContenTiTle>
                    <ContenList>
                        <CenterName>网口标志</CenterName>
                        <CenterInputOuter>
                            <Input
                                value={this.state.netPortSymbol}
                                name={'netPortSymbol'}
                                onChange={(e) => this._handleChange(e)}
                                placeholder={tipsObj.netPortSymbol}
                                title={tipsObj.netPortSymbol}
                            /></CenterInputOuter>
                    </ContenList>

                    <ContenList>
                        <CenterName>IP链路标志</CenterName>
                        <CenterInputOuter>
                            <Input
                                value={this.state.ipAddressSymbol}
                                name={'ipAddressSymbol'}
                                onChange={(e) => this._handleChange(e)}
                                placeholder={tipsObj.ipAddressSymbol}
                                title={tipsObj.ipAddressSymbol}
                            /></CenterInputOuter>
                    </ContenList>

                    <ContenList>
                        <CenterName>VlanId</CenterName>
                        <CenterInputOuter>
                            <Input
                                value={this.state.VlanId}
                                name={'VlanId'}
                                onChange={(e) => this._handleChange(e)}
                                placeholder={tipsObj.VlanId}
                                title={tipsObj.VlanId}
                            /></CenterInputOuter>
                    </ContenList>

                    <ContenList>
                        <CenterName>IP地址</CenterName>
                        <CenterInputOuter>
                            <Input
                                value={this.state.ipAddress}
                                name={'ipAddress'}
                                onChange={(e) => this._handleChange(e)}
                                placeholder={tipsObj.ipAddress}
                                title={tipsObj.ipAddress}
                            /></CenterInputOuter>
                    </ContenList>

                    <ContenList>
                        <CenterName>子网掩码</CenterName>
                        <CenterInputOuter>
                            <Input
                                value={this.state.netmask}
                                name={'netmask'}
                                onChange={(e) => this._handleChange(e)}
                                placeholder={tipsObj.netmask}
                                title={tipsObj.netmask}
                            /></CenterInputOuter>
                    </ContenList>

                    <ContenList>
                        <CenterName>是否虚拟IP</CenterName>
                        <CenterInputOuter>
                            <Select
                                value={this.state.virtualIpBoolean}
                                style={{width: 400}}
                                onChange={(e) => this._handleVirtualIpBooleanChange(e)}
                                placeholder={tipsObj.virtualIpBoolean}
                            >
                                <Option value="True">True</Option>
                                <Option value="Disable">False</Option>
                            </Select>
                        </CenterInputOuter>
                    </ContenList>

                    <ContenList>
                        <CenterName>MTU</CenterName>
                        <CenterInputOuter>
                            <Input
                                value={this.state.mtu}
                                name={'mtu'}
                                onChange={(e) => this._handleChange(e)}
                                placeholder={tipsObj.mtu}
                                title={tipsObj.mtu}
                            /></CenterInputOuter>
                    </ContenList>

                    <ContenList>
                        <CenterName>网口是否启用</CenterName>
                        <CenterInputOuter>
                            <Select
                                value={this.state.OpenNetPortBoolean}
                                style={{width: 400}}
                                onChange={(e) => this._handleOpenNetPortBooleanChange(e)}
                                placeholder={tipsObj.OpenNetPortBoolean}
                            >
                                <Option value="Enable">Enable</Option>
                                <Option value="Disable">Disable</Option>
                            </Select>
                        </CenterInputOuter>
                    </ContenList>

                </Modal>
            </div>
        )
    }

    delRow = (row, e) => {
        const {dispatch} = this.props

        var $this = this
        Modal.confirm({
            title: '确定要删除 ID 为 ' + row.ID + ' 的数据么？',
            content: '删除后无法找回',
            okText: '确认',
            cancelText: '取消',
            onOk: function () {
                let sendData = JSON.parse(JSON.stringify($this.state.configData))
                let newPData = []
                sendData.config.dpData.forEach(a => {
                    if (a.ID != row.ID) {
                        newPData.push(a)
                    }
                })
                sendData.config.dpData = newPData

                const sessionData = new Session();
                const csrf = ((sessionData || {}).session || {}).csrfToken;
                const authToken = ((sessionData || {}).session || {}).authToken;
                let headers = {'X-CSRF-TOKEN': csrf}
                if (authToken) {
                    headers['Authorization'] = "Bearer " + authToken
                }

                axios({
                    baseURL: '/api/db',
                    headers: headers,
                    method: "PATCH",
                    url: '/dp/' + sendData._id,
                    data: sendData,
                    //
                }).then(res => {
                    $this.handleCancel()
                    var configData = res.data.config
                    $this.setState({
                            configData: res.data,
                            dpData: configData.dpData || []
                        }
                    )
                    dispatch(Notification.success({
                        title: '提示',
                        message: `DP参数删除成功！`
                    }));
                })
            }
        });
    }
}

Collection = connect(
    (state) => ({})
)(Collection);

export default Collection;